

//
//  WBUserAccount.swift
//  新浪微博练习
//
//  Created by 韩旭 on 16/11/27.
//  Copyright © 2016年 韩旭. All rights reserved.
//

import UIKit

private let userAccountKey = "userAccountKey"

class WBUserAccount: NSObject {
    //单例
    static let shared: WBUserAccount = WBUserAccount()
    
    /// 眤称
    var screen_name: String?
    /// 用户id
    var uid: String?
    /// token
    var access_token: String?
    /// 用户的头像
    var avatar_large: String?
    /// 过期秒数
    var expires_in: Double = 0 {
        didSet {
            expires_date = Date(timeInterval: expires_in, since: Date())
        }
    }
    /// 过期的日期
    var expires_date: Date?
    ///是否登陆
    var isLogin:Bool {
       return access_token != nil && expires_date!.compare(Date()) == .orderedDescending
    }
    ///description 对象的描述信息
    override var description: String{
        return dictionaryWithValues(forKeys: ["access_token", "expires_date", "uid", "screen_name", "avatar_large"]).description
    }
    
   // 构造函数
    override init() {
        super.init()
        
        //从缓存读取字典
        read()
    }
    ///异常处理
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
    ///读取用户信息
    func read() {
       //从缓存中读取usercount的字典
        if let userDict = UserDefaults.standard.value(forKey: userAccountKey) as?[String:Any]{
            //使用userDict给当前单例赋值
            setValuesForKeys(userDict)
        }
        
    }
    
    
    ///缓存用户信息登陆成功之后马上调用
    func save (dict: [String:Any]) {
        //先用字典给单例的属性赋值
        setValuesForKeys(dict)
        //模型转字典
        let userAccountDic = dictionaryWithValues(forKeys: ["screen_name", "uid", "access_token", "avatar_large", "expires_date"])
        UserDefaults.standard.set(userAccountDic, forKey: userAccountKey)
    }
}




















